package com.wang.lotterysystem.service.manager.operator;

import com.wang.lotterysystem.controller.enums.ActivityPrizeStatusEnum;
import com.wang.lotterysystem.dao.mapper.ActivityMapper;
import com.wang.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.wang.lotterysystem.service.dto.activity.ActivityStatusConvertDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 活动状态转换类
 * 实现了状态转换抽象类
 */
@Component
public class ActivityOperator extends AbstractActivityOperator{

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    /**
     * 判断是否需要进行状态转换
     * @param statusConvertDTO 状态转换参数
     * @return true-->需要 / false-->不需要
     */
    @Override
    public Boolean needConvert(ActivityStatusConvertDTO statusConvertDTO) {
        //判断后续需要校验的参数是否为空
        if (statusConvertDTO.getActivityId() == null ||
                statusConvertDTO.getActivityTargetStatus() == null){
            return false;
        }

        //校验活动状态是否和数据库中的一致,如果一致就是翻转过的
        String activityStatus =
                activityMapper.selectById(statusConvertDTO.getActivityId()).getStatus();
        if (activityStatus.equals(statusConvertDTO.getActivityTargetStatus().name())){
            return false;
        }

        //校验活动奖品是否全部抽完
        int count = activityPrizeMapper.countRunningPrizeByActivityId(
                statusConvertDTO.getActivityId(),
                ActivityPrizeStatusEnum.INIT.name()
        );

        if (count > 0) {
            //如果count>0,说明还存在没抽完的奖品
            return false;
        }

        return true;
    }

    @Override
    public Boolean convertStatus(ActivityStatusConvertDTO statusConvertDTO) {

        activityMapper.convert(
                statusConvertDTO.getActivityId(),
                statusConvertDTO.getActivityTargetStatus().name()
        );

        return true;
    }
}